import os

from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from alipay import AliPay
from django.views import View
from apps.orders.models import *
from apps.payment.models import Payment
from meiduo_mall.settings.dev import LOGGER
from django.http import *
from utils.response_code import RETCODE


class PaymentView(LoginRequiredMixin, View):
    def get(self, request, order_id):
        """返回支付宝付款接口"""
        user = request.user
        # 查询支付的订单
        try:
            order = OrderInfo.objects.get(user=user, order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            LOGGER.error(e)
            return HttpResponseForbidden('订单信息错误')

        # 创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url 可以不填 但是必须填写
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 支付宝登陆链接生成
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,      # 订单编号
            total_amount=str(order.total_amount),   # 订单总额
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 支付宝链接 拼接
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentStatusView(LoginRequiredMixin, View):
    def get(self, request):
        """回调地址生成"""
        query_dict = request.GET
        data = query_dict.dict()
        # 获取并从请求参数中剔除signature
        sign = data.pop('sign')
        # 创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url 可以不填 但是必须填写
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 支付宝的二次校验
        success = alipay.verify(data, sign)
        # 判断校验结果
        if success:
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存Payment模型类数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])

            # 响应trade_id
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return HttpResponseForbidden('非法请求')
